<?php
/* MyMeeting is an online meeting management software.
 * Copyright (C) 2009 Government Of Malaysia
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * @author: Abdullah Zainul Abidin, Nuhaa All Bakry
 *          Eavay Javay Barnad, Sarogini Muniyandi, Teow Jit Huan
 *
 */

class MeetingsController extends AppController {


    /**
     * Define $name
     *
     */
    var $name = 'Meetings';
    /**
     * Define $helpers
     *
     */
    var $helpers = array('Html', 'Form', 'DatePicker','Comment', 'Ajax', 'Javascript','MultiFile','Text');
    /**
     * Define $components
     *
     */
    var $components = array('RequestHandler', 'Email','MultiFile');
    /**
     * Define $uses
     *
     */
    var $uses = array('Meeting','Notification','Template','Todo','Decision','Group','Hash','Meetingtodo','Attendance');


    var $paginate = array(
    'fields'=>array('Meeting.id','Meeting.meeting_num','Meeting.meeting_title','Meeting.meeting_date','Meeting.venue'),
    'order'=>array('Meeting.meeting_date'=>'desc','Meeting.id'=>'desc'),
    'contain'=>array('Attendance','Notification'),
    'limit'=>25
    );
    /**
     * Define $_string_to_log_message
     *
     */
    var $_string_to_log_message = '';
    /**
     * Define $_string_to_log_to
     *
     */
    var $_string_to_log_to = '';

    /**
     * Describe editminutes
     *
     * @param $committee
     * @return null
     */
    function editminutes($committee) {
        $this->Meeting->Committee->recursive=-1;
        $this->Meeting->recursive=-1;
        $this->Meeting->Behaviors->detach('Comment');
        $this->set('dcommittee',$this->dcommittee);
        if(!empty($this->data)){
            $this->Meeting->save($this->data);
            $this->redirect(array('committee'=>$this->dcommittee['Committee']['short_name'],'action'=>'view','id'=>$this->data['Meeting']['id'],'controller'=>'meetings')); 
        }
        if (empty($this->data)) {
            $this->data = $this->Meeting->read(null, $this->params['meetingid']);
            $this->set('data',$this->data);
        }
    }

    /**
     * Describe announcedecisions
     *
     * @param $committee
     * @return null
     */
    function announcedecisions($committee) {
        $this->set('dcommittee',$this->dcommittee);
        if(isset($this->params['meetingid'])){
            //only secretariat have permission to ask for status update
            if(!$this->Meeting->Attendance->isSecretariat($this->params['meetingid'],$this->Auth->user('id'))){
                $this->notpermit();
            }
            $this->Decision->notifyalluser($this->params['meetingid']);
            $this->Session->setFlash(__('Notifications of decisions sent to users', true));
            $this->redirect($this->referer(null,true));
        }
        else{
            $this->Session->setFlash(__('Invalid meeting id', true));
            $this->redirect($this->referer(null,true));
        }
    }

    /**
     * Describe index
     *
     * @param $committee
     * @return null
     */
    function index($committee) {
        $this->Committee->unbindModel( array('hasMany' => array('Wfmodel','Announcement','Item','Group','Decision','Userstatus','Groupstatus','Meeting','Todo')),false );
        $this->Committee->unbindModel( array('hasAndBelongsToMany'=> array('User')),false );
        $this->Meeting->Behaviors->detach('Comment');
        $this->Meeting->Behaviors->detach('MultiFile');
        $this->Meeting->unbindModel( array('hasMany'=> array('Todo','Decision')),false );
        $this->Meeting->unbindModel( array('hasAndBelongsToMany'=> array('User')),false );

        $meetings=$this->paginate('Meeting',array('committee_id'=>$this->dcommittee['Committee']['id']));
        if(!empty($meetings)){
            $meetings=$this->fixupauth($meetings,'Meeting');
        }
        
        $this->set('meetings',$meetings);
        $this->set('committee',$committee);
    }

    /**
     * Describe indexfollowup
     *
     * @param $committee
     * @param $meetingid
     * @return null
     */
    function indexfollowup($committee,$meetingid) {
        $dcommittee=$this->Meeting->Committee->findByShortName($committee);
        $this->set('dcommittee',$dcommittee);
        $meetingid=$this->Meeting->findById($meetingid);
        $this->set('meetingid',$meetingid);
        $this->Meeting->recursive = 1;
        $this->set('meetings',$this->paginate('Meeting',array('conditions'=>array('committee_id'=>$dcommittee['Committee']['id'] ,'parent_id'=>$meetingid['Meeting']['id']) )));
        $this->set('allow_add_meeting',true);
        $this->set('committee',$committee);
    }

    /**
     * Describe view
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function view($committee,$id = null) {
        $this->Committee->User->unbindModel(array('hasAndBelongsToMany'=>array('Committee','Meeting','Decision','Group'),'hasMany'=>array('Announcement','Meetingtodo','Userstatus','Groupstatus')),false );
        $this->Committee->unbindModel(array('hasAndBelongsToMany'=>array('User'),'hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Userstatus','Groupstatus','Wfmodel','Todo')),false );
        
        //check permission
        if($this->Auth->user('superuser')==0){
            $permit=$this->meetingPermission($id,array('View'));
            if(empty($permit['View'])){
                $this->notpermit();
            }
        }
        if (!$id) {
            $this->Session->setFlash(__('Invalid Meeting.', true));
            $this->redirect(array('action'=>'index'));
        }
        $this->Meeting->Decision->Behaviors->attach('Comment');
        $meeting=$this->Meeting->find(
            'first',array(
                'conditions'=>array(
                    'Meeting.id'=>$id,
                ),
                'contain'=>array(
                    'Committee.name',
                ),
                'fields'=>array(
                    'id',
                    'meeting_num',
                    'meeting_title',
                    'meeting_date',
                    'venue',
                    'minutes_raw',
                    'agenda'
                ),
            )
        );
        
        $this->set('announced',($this->Notification->checkSent($id,'announce minute')));
        $this->set('invited',($this->Notification->checkSent($id,'invite')));
        $this->set('approval_sent',($this->Notification->checkSent($id,'send for approval')));
        $this->set('reapproval_sent',($this->Notification->checkSent($id,'send for reapproval')));
        $this->set('minutes_approved',($this->Notification->checkSent($id,'minutes approved')));
        $this->set('minute_comment',($this->Notification->checkSent($id,'minute comment')));
        
        $secretariat[$id] =$this->Meeting->Attendance->isSecretariat($id,$this->Auth->user('id'));
        $chairperson =$this->Meeting->Attendance->getChairperson($id);
        $this->set(compact('secretariat','chairperson'));
        
        $this->Meeting->Behaviors->detach('MultiFile');
        $this->Meeting->Behaviors->detach('Comment');
        $cont='';
        //if($secretariat[$id] ==0){
            $permission=$this->Session->read('permission');
            if($permission['Meeting']['View']==1){
                $cont='';
            }elseif($permission['Meeting -Invited']['View']==1){
                $att=$this->Meeting->Attendance->find('all',array('conditions'=>array('Attendance.user_id'=>$this->Auth->user('id'))));
                $cont['Meeting.id']=set::extract($att,'{n}.Attendance.meeting_id');
            }elseif($permission['Meeting -Attended']['View']==1){
                $att=$this->Meeting->Attendance->find('all',array('conditions'=>array('Attendance.user_id'=>$this->Auth->user('id'),'Attendance.attended'=>1)));
                $cont['Meeting.id']=set::extract($att,'{n}.Attendance.meeting_id');
            }
            $this->set('permission',$permission);
        //}
        $prev=$this->Meeting->find('first',array(
            'conditions'=>array(
                'Meeting.committee_id'=>$this->dcommittee['Committee']['id'],
                'Meeting.deleted=0',
                'or'=>array(
                    'Meeting.meeting_date<\''.$meeting['Meeting']['meeting_date'].'\'',
                    'and'=>array(
                        'Meeting.meeting_date=\''.$meeting['Meeting']['meeting_date'].'\'',
                        'Meeting.id<'.$meeting['Meeting']['id'],
                    )
                ),
                $cont
            ),
            'fields'=>array(
                'id',
                'meeting_num',
            ),
            'contain'=>false,
            'order'=>array(
                'Meeting.meeting_date'=>'desc',
                'Meeting.id'=>'desc'
            ),
        ));    
        $next=$this->Meeting->find('first',array(
            'conditions'=>array(
                'Meeting.committee_id'=>$this->dcommittee['Committee']['id'],
                'Meeting.deleted=0',
                'or'=>array(
                    'Meeting.meeting_date>\''.$meeting['Meeting']['meeting_date'].'\'',
                    'and'=>array(
                        'Meeting.meeting_date=\''.$meeting['Meeting']['meeting_date'].'\'',
                        'Meeting.id>'.$meeting['Meeting']['id'],
                    )
                ),
                $cont
            ),
            'fields'=>array(
                'id',
                'meeting_num',
            ),
            'contain'=>false,
            'order'=>array(
                'Meeting.meeting_date'=>'asc',
                'Meeting.id'=>'asc'
            ),
        ));
        if($prev){
            $this->set('prev',$prev);
        }
        if($next){
            $this->set('next',$next);
        }                                                                                       
        $this->set('meeting', $meeting);
        
        
        // for search dropdowns
        $projects = $this->Meeting->Decision->Item->find(
            'list',array(
                'conditions'=>array(
                    'Item.committee_id'=>$this->dcommittee['Committee']['id'],
                ),
                'order'=>'Item.name ASC',
            )
        );
        $groups = $this->Group->find(
            'list',array(
                'conditions'=>array(
                    'Group.committee_id'=>$this->dcommittee['Committee']['id'],
                ),
                'order'=>'Group.name ASC',
            )
        ); 
        $users_tmp = $this->Committee->User->getUsersPerCommittee($this->dcommittee['Committee']['id']);
        foreach ($users_tmp as $key => $user) { 
            $users[$user['User']['id']] = $user['User']['name'];
        }
        $this->set(compact('projects','groups','users'));
        
       if (!empty($this->data['Search']['item']) || !empty($this->data['Search']['group']) || !empty($this->data['Search']['user'])) {
            $decision = $this->Meeting->Decision->search($this->data['Search']);
        }else{
            $decision=$this->Meeting->Decision->find(
                'all',array(
                    'conditions'=>array(
                        'Decision.meeting_id'=>$id,
                        'Decision.deleted'=>0
                    ),
                    'order'=>array(
                        'Decision.lft asc',
                    )
                )
            );
        }
        if(isset($decision[0])){$this->set('addminute',1);}
        //User & Group Check
        $new_decision = array();
        foreach ($decision as $decisions ) {
            //unset the status if the owner is not implementor
            $decisions=$this->Meeting->Decision->unset_nonImpstatus($decisions);
            //if dun have User and Group no display
            if ( count($decisions['Group']) > 0 || count($decisions['User']) > 0 ) {
                $new_decision = array_merge( $new_decision, array($decisions) );
            };
        }
        $decision = $new_decision;
        $this->set('decisions',$decision);
       
        $arr=$this->Meeting->Decision->Check($decision,$this->Auth->user('id'));
        $this->set('A',$arr[0]);
        $this->set('N',$arr[1]);
        $this->set('allow',$arr[2]);
        $this->set('noupdated',$arr[3]);
        
        $permiss=array();
        if($this->Auth->user('superuser')==0 && $secretariat[$id]==0){
            foreach($decision as $d){
                $permiss[$d['Decision']['id']]=$this->decisionPermission($d);
            }
        }
        $this->set('permiss',$permiss);
    }

    /**
     * Describe edit_invitation
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function edit_invitation($committee,$id){
        $this->Meeting->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Meeting->unbindModel(array('hasMany'=>array('Decision','Todo','Notification'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Meeting->Behaviors->detach('MultiFile');
        $this->Meeting->Behaviors->detach('Comment');
        $this->set('dcommittee',$this->dcommittee);
        if(!empty($this->data)) {
            $this->Template->save($this->data);
            $meetingdata['id']=$id;
            $meetingdata['invite_date']=strlen($this->data['Template']['invite_date'])?$this->data['Template']['invite_date']:null;
            $this->Meeting->save($meetingdata);
            $this->redirect(array('committee'=>$this->dcommittee['Committee']['short_name'],'action'=>'invite','id'=>$this->data['Meeting']['id']));
        }
        $meeting=$this->Meeting->read(null,$id);
        $template=$this->Template->findTemplate('invite',$meeting['Meeting']);
        if($template){
            $this->set('template_type','invite');
            $this->set('template',$template);
            $this->set('meeting',$meeting);
        }
        $this->render("edit_template");
    }

    /**
     * Describe edit_cancelation
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function edit_cancelation($committee,$id){
        $this->Meeting->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Meeting->unbindModel(array('hasMany'=>array('Decision','Todo','Notification'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Meeting->Behaviors->detach('MultiFile');
        $this->Meeting->Behaviors->detach('Comment');
       
        $this->set('dcommittee',$this->dcommittee);
        if(!empty($this->data)) {
            $this->Template->save($this->data);
            $this->redirect(array('committee'=>$this->dcommittee['Committee']['short_name'],'action'=>'cancel','id'=>$this->data['Meeting']['id']));
        }
        $this->Meeting->Behaviors->detach('SoftDeletable');
        $meeting=$this->Meeting->read(null,$id);
        $template=$this->Template->findTemplate('cancel',$meeting['Meeting']);
        if($template){
            $this->set('template_type','cancel');
            $this->set('template',$template);
            $this->set('meeting',$meeting);
        }
        $this->render("edit_template");
    }
    
    /**
     * Describe edit_approval
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function edit_approval($committee,$id){
        $this->Meeting->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Meeting->unbindModel(array('hasMany'=>array('Decision','Todo','Notification'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Meeting->Behaviors->detach('MultiFile');
        $this->Meeting->Behaviors->detach('Comment');
       
        $this->set('dcommittee',$this->dcommittee);
        if(!empty($this->data)) {
			debug($this->data);
            $this->Template->save($this->data);
            $this->redirect(array('committee'=>$this->dcommittee['Committee']['short_name'],'action'=>'approval','id'=>$this->data['Meeting']['id']));
        }
        $this->Meeting->Behaviors->detach('SoftDeletable');
        $meeting=$this->Meeting->read(null,$id);
        $template=$this->Template->findTemplate('send for approval',$meeting['Meeting']);
        if($template){
            $this->set('template_type','send for approval');
            $this->set('template',$template);
            $this->set('meeting',$meeting);
        }
        $this->render("edit_template");
    }

    /**
     * Describe invite
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function invite($committee,$id){
        $this->Meeting->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Meeting->unbindModel(array('hasMany'=>array('Decision','Todo','Notification'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Meeting->Behaviors->detach('MultiFile');
        $this->Meeting->Behaviors->detach('Comment');
    
        $meeting=$this->Meeting->read(null,$id);
        $this->set('meeting',$meeting);
        $meeting['Link']['meeting']=array('committee'=>urlencode($this->dcommittee['Committee']['short_name']),'controller'=>'meetings','action'=>'view','id'=>$id);
        $meeting['Link']['confirm']='/hash/%hash';
        $template=$this->Template->processTemplate('invite',$meeting);
        $this->set('template',$template);
    }

    /**
     * Describe cancel
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function cancel($committee,$id){
        $this->Meeting->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Meeting->unbindModel(array('hasMany'=>array('Decision','Todo','Notification'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Meeting->Behaviors->detach('MultiFile');
        $this->Meeting->Behaviors->detach('Comment');
        
        $this->set('dcommittee',$this->dcommittee);
        $this->Meeting->Behaviors->detach('SoftDeletable');
        $meeting=$this->Meeting->read(null,$id);
        $template=$this->Template->processTemplate('cancel',$meeting);
        if($template){
            $this->set('template',$template);
            $this->set('meeting',$meeting);
        }
    }

    /**
     * Describe send_emails
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function send_emails($committee,$id){
        $meeting=$this->Meeting->read(null,$id);
        $prev_meeting=$this->Session->read('prev_meeting');
        $this->Session->delete('prev_meeting');
        $meeting['OldMeeting']=$prev_meeting['Meeting'];
        $meeting['Link']['confirm']='/hash/%hash';
        $meeting['Link']['meeting']=array('committee'=>urlencode($this->dcommittee['Committee']['short_name']),'controller'=>'meetings','action'=>'view','id'=>$id);
            
        for($i=0;$i<3;$i++){
            switch($i){
            case 0:   //send invitation
                $template=$this->Template->processTemplate('invite',$meeting);
                $users=$this->Meeting->User->find('all',array('conditions'=>array('User.id'=>($this->Session->read('to_invite')))));
                $this->Session->delete('to_invite');
                break;
            case 1:   //send change notification
                $template=$this->Template->processTemplate('change',$meeting);
                $users=$this->Meeting->User->find('all',array('conditions'=>array('User.id'=>($this->Session->read('to_notify_changes')))));
                $this->Session->delete('to_notify_changes');
                break;
            case 2:   //send uninvite 
                $template=$this->Template->processTemplate('uninvite',$meeting);
                $users=$this->Meeting->User->find('all',array('conditions'=>array('User.id'=>($this->Session->read('to_uninvite')))));
                $this->Session->delete('to_uninvite');
                break;
            }
            $template1=$template;
            foreach($users as $user){
                if($i===0){
                    $att = $this->Meeting->Attendance->find('first',array('conditions'=>array('meeting_id'=>$id,'user_id'=>$user['User']['id'])));
                    $hash = $this->Hash->find('all',array('conditions'=>array('model'=>'Attendance','foreign_key'=>$att['Attendance']['id'],'hash_type'=>'confirm'),'fields'=>array('hash')));
                    count($hash) ? $data['hash']= $hash[0]['Hash']['hash'] : $data['hash']='';
                    $template1['Template']['template']=$this->Meeting->replacetemplate($template['Template']['template'],$data);
                }
                $this->Meeting->sendEmail($meeting['Meeting'],$template1,$user['User'],date("Y-m-d H:i:s",strtotime($meeting['Meeting']['invite_date'].' 07:30:00')));
            }
        }
        $this->Session->setFlash(__('Emails set to send',true));
        $this->redirect(array('committee'=>$committee,'action'=>'index'));
    }

    /**
     * Describe send_invite
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function send_invite($committee,$id){
        $meeting=$this->Meeting->read(null,$id);
        $meeting['Link']['meeting']=array('committee'=>urlencode($this->dcommittee['Committee']['short_name']),'controller'=>'meetings','action'=>'view','id'=>$id);
        $meeting['Link']['confirm']='/hash/%hash';
        $template=$this->Template->processTemplate('invite',$meeting);
        if($template){
            $template1=$template;
            foreach($meeting['User'] as $user){
                $att = $this->Meeting->Attendance->find('first',array('conditions'=>array('meeting_id'=>$meeting['Meeting']['id'],'user_id'=>$user['id'])));
                $hash = $this->Hash->find('all',array('conditions'=>array('model'=>'Attendance','foreign_key'=>$att['Attendance']['id'],'hash_type'=>'confirm'),'fields'=>array('hash')));
                count($hash) ? $data['hash']= $hash[0]['Hash']['hash'] : $data['hash']='';
                $template1['Template']['template']=$this->Meeting->replacetemplate($template['Template']['template'],$data);
                $this->Meeting->sendEmail($meeting['Meeting'],$template1,$user,null);
            }
            $this->Session->setFlash(__('The invitations has been sent',date("Y-m-d H:i:s",strtotime($meeting['Meeting']['invite_date'].' 07:30:00'))));
        }
        $this->redirect(array('committee'=>$committee,'action'=>'index'));
    }

    /**
     * Describe send_cancel
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function send_cancel($committee,$id){
        $this->Meeting->Behaviors->detach('SoftDeletable');
        $this->Meeting->Attendance->Behaviors->detach('SoftDeletable');
        $meeting=$this->Meeting->read(null,$id);
        $template=$this->Template->processTemplate('cancel',$meeting);
        if($template){
            foreach($meeting['User'] as $user){
                $this->Meeting->sendEmail($meeting['Meeting'],$template,$user,null);
            }
            $this->Session->setFlash(__('The cancelations has been sent', true));
        }
        $this->redirect(array('committee'=>$committee,'action'=>'index'));
    }

    /**
     * Describe add
     *
     * @param $committee
     * @return null
     */
    function add($committee) {
        $this->Meeting->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        if (!empty($this->data)) {
            $this->Meeting->create();
            if (isset($this->data['Meeting']['sendnow'])) $this->data['Meeting']['invite_date'] = date('Y-m-d');
            $this->data['Session']['user_id']=$this->Auth->user('id');
            
            //check the number of chairperson
            $chairperson=$this->Meeting->Attendance->CheckChairperson($this->data['User']);
            if($chairperson==0){
                $this->Session->setFlash(__('Please choose a member as chairperson.', true));
            }elseif($chairperson>1){
                $this->Session->setFlash(__('You have choosen more than one chairperson. Only one member is allowed to be chairperson.', true));
            }elseif($this->Meeting->Attendance->CheckSecretariat($this->data['User'])==0){
                $this->Session->setFlash(__('Please select the secretariat.', true));
            }else{
                if ($this->Meeting->save($this->data)) {
                    $meeting_id=$this->Meeting->getLastInsertID();
                    
                    $this->Meeting->Attendance->saveAttendAs($this->data,$meeting_id);
                    $this->Meeting->query("DELETE FROM attendances WHERE user_id=0 AND meeting_id=".$meeting_id );
                    // save data inside hash table for attendance confirmation
                    $attendance = $this->Meeting->Attendance->find('all',array('conditions'=>array('Meeting.id'=>$meeting_id))); 
                    $this->Hash->insertToHashTable('confirm',$attendance);
            
                    $todos=$this->Meeting->Committee->Todo->find('all',array('conditions'=>array('committee_id'=>$this->dcommittee['Committee']['id'])));
                    foreach($todos as $todo){
                        $ctodo['name']=$todo['Todo']['name'];
                        $ctodo['priority']=$todo['Todo']['priority'];
                        $ctodo['user_id']=$this->Auth->user('id');
                        $ctodo['meeting_id']=$meeting_id;
                        $this->Meeting->Todo->create();
                        $this->Meeting->Todo->save($ctodo);
                    } 

                    $templates=$this->Template->find('all',array('conditions'=>array('foreign_key'=>$this->dcommittee['Committee']['id'],'model'=>'Committee')));
                    foreach($templates as $template){
                        $ctemplate['type']=$template['Template']['type'];
                        $ctemplate['title']=$template['Template']['title'];
                        $ctemplate['description']=$template['Template']['description'];
                        $ctemplate['template']=$template['Template']['template'];
                        $ctemplate['foreign_key']=$meeting_id;
                        $ctemplate['model']='Meeting';
                        $this->Template->create();
                        $this->Template->save($ctemplate);
                    }
                    foreach($attendance as $a){
                        $this->Meeting->create_usercal($a['User']['id'],$a['User']['username']);
                    }
                    
                    $this->Meeting->create_cal($this->dcommittee['Committee']['id']);
                    $this->Session->setFlash(__('The Meeting has been saved', true));
                    if(configure::read('e_invite')==1){
                        $this->redirect(array('committee'=>$this->dcommittee['Committee']['short_name'],'action'=>'invite','id'=>$meeting_id));
                    }else{
                        $this->redirect(array('committee'=>$this->dcommittee['Committee']['short_name'],'action'=>'index'));
                    }
                } else {
                    $this->Session->setFlash(__('The Meeting could not be saved. Please, try again.', true));
                }
            }
        }
        $this->set('groups',$this->Meeting->Attendance->User->Group->find('list',array('conditions'=>array('committee_id'=>$this->dcommittee['Committee']['id']))));
        $this->set('users', $this->Meeting->Attendance->User->getUsersPerCommittee($this->dcommittee['Committee']['id']));
        $this->set('nextnum',$this->Meeting->nextnumber($this->dcommittee['Committee']['id']));
        $this->set('defaulttitle',$this->Meeting->meetingtitle($this->dcommittee['Committee']['id']));
    }

    //add follow-up meeting

    /**
     * Describe addfollowup
     *
     * @param $committee
     * @param $meetingid
     * @return null
     */
    function addfollowup($committee, $meetingid){
        $dcommittee=$this->Meeting->Committee->findByShortName($committee);
        $this->set('dcommittee',$dcommittee);
        $meetingid=$this->Meeting->findById($meetingid);
        $this->set('meetingid',$meetingid);

        if (!empty($this->data)) {

            $this->Meeting->create();
            if (isset($this->data['Meeting']['sendnow'])) $this->data['Meeting']['invite_date'] = date('Y-m-d');
            $this->data['Session']['user_id']=$this->Auth->user('id');
            if ($this->Meeting->save($this->data)) {
                $meeting_id=$this->Meeting->getLastInsertID();
                $todos=$this->Meeting->Committee->Todo->find('all',array('conditions'=>array('committee_id'=>$dcommittee['Committee']['id'])));
                foreach($todos as $todo){
                    $ctodo['name']=$todo['Todo']['name'];
                    $ctodo['priority']=$todo['Todo']['priority'];
                    $ctodo['meeting_id']=$meeting_id;
                    $this->Meeting->Todo->create();
                    $this->Meeting->Todo->save($ctodo);
                }   
                $this->Session->setFlash(__('The Meeting has been saved', true));


                $this->redirect(array('committee'=>$dcommittee['Committee']['short_name'],'meetingid'=>$meetingid['Meeting']['id'],'action'=>'indexfollowup'));
            } else {
                $this->Session->setFlash(__('The Meeting could not be saved. Please, try again.', true));
            }
        }

        $this->set('groups',$this->Meeting->User->Group->find('list',array('conditions'=>array('committee_id'=>$dcommittee['Committee']['id']))));
        $this->set('users', $this->Meeting->User->getUsersPerCommitteeList($dcommittee['Committee']['id']));
    }

    /**
     * Describe minutes
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function minutes($committee,$id = null) {
        $this->set('dcommittee',$this->dcommittee);
        if (!$id) {
            $this->Session->setFlash(__('Invalid Meeting.', true));
            $this->redirect(array('action'=>'index'));
        }
        $this->set('meeting', $this->Meeting->read(null, $id));
        $decision=$this->Meeting->Decision->find('all',array('conditions'=>array('Decision.meeting_id'=>$id)));
        $this->set('decision',$decision); 
    $attended = $this->Meeting->User->Attendance->find('all',array('conditions'=>array('meeting_id'=>$id,'attended'=>1),'','ORDER BY User.username'));
    $attended = $this->User->Protocol->softByProtocol($attended);
        $this->set('attended', $attended);
        $this->set('titles',$this->Meeting->User->Title->find('list'));
        $notattended = $this->Meeting->User->Attendance->find('all',array('conditions'=>array('meeting_id'=>$id,'attended'=>0)));
        $this->set('notattended', $notattended);
        $this->render('minutes','popup');
    }

    /**
     * Describe previewemails
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function previewemails($committee,$id) {
        $this->Meeting->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Meeting->Behaviors->detach('Comment');
        $this->Meeting->unbindModel(array('hasMany'=>array('Decision','Todo','Notification'),'hasAndBelongsToMany'=>array('User','Membership')),false);
       
        //call data for getting id to save change
        $meeting=$this->Meeting->read(null,$id);
        $invite=$this->Template->findTemplate('invite',$meeting['Meeting']);
        $change=$this->Template->findTemplate('change',$meeting['Meeting']);
        $uninvite=$this->Template->findTemplate('uninvite',$meeting['Meeting']);
        
        //save data
        if(isset($this->data)){
            $template['template']=$this->data['Template']['invite'];
            $template['id']=$invite['Template']['id'];
            $this->Template->save($template);
            $template['template']=$this->data['Template']['change'];
            $template['id']=$change['Template']['id'];
            $this->Template->save($template);
            $template['template']=$this->data['Template']['uninvite'];
            $template['id']=$uninvite['Template']['id'];
            $this->Template->save($template);
            if(Validation::date($this->data['Template']['invite_date'])){
                $this->data['Meeting']['invite_date']=$this->data['Template']['invite_date'];
                $this->Meeting->save($this->data);
                $meeting=$this->Meeting->read(null,$id);
            }
        }
        
        //find the recipient name
        $to_invite=$this->Session->read('to_invite');
        $to_uninvite=$this->Session->read('to_uninvite');
        $to_notify_changes=$this->Session->read('to_notify_changes');
        $this->set('to_invite',set::extract($this->Meeting->User->find('all',array('conditions'=>array('User.id'=>$to_invite))),'{n}.User.name'));
        $this->set('to_uninvite',set::extract($this->Meeting->User->find('all',array('conditions'=>array('User.id'=>$to_uninvite))),'{n}.User.name'));
        $this->set('to_notify_changes',set::extract($this->Meeting->User->find('all',array('conditions'=>array('User.id'=>$to_notify_changes))),'{n}.User.name'));
        
        //find the needed data in the template
        $meeting['Link']['meeting']=array('committee'=>urlencode($this->dcommittee['Committee']['short_name']),'controller'=>'meetings','action'=>'view','id'=>$id);
        $prev_meeting=$this->Session->read('prev_meeting');
        $meeting['OldMeeting']=$prev_meeting['Meeting'];
        
        $this->set('invite',$this->Template->processTemplate('invite',$meeting));
        $this->set('change',$this->Template->processTemplate('change',$meeting));
        $this->set('uninvite',$this->Template->processTemplate('uninvite',$meeting));
        $this->set('dcommittee',$this->dcommittee);
        $this->set('meeting',$meeting);
    }

    /**
     * Describe editemails
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function editemails($committee=null,$id = null) {
        $this->Meeting->unbindModel(array('hasMany'=>array('Decision','Todo','Notification'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Meeting->Behaviors->detach('Comment');
        $this->Meeting->Behaviors->detach('MultiFile');
        $this->Meeting->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Workflow','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
    
        $meeting=$this->Meeting->read(null,$id);
        $this->set('meeting',$meeting);
        $this->set('invite',$this->Template->findTemplate('invite',$meeting['Meeting']));
        $this->set('change',$this->Template->findTemplate('change',$meeting['Meeting']));
        $this->set('uninvite',$this->Template->findTemplate('uninvite',$meeting['Meeting']));
        $this->set('dcommittee',$this->dcommittee);
    }

    /**
     * Create notifications when comments are made
     *
     * @param $meeting_id 
     * @param $comment_id
     * @return null
     */
    function sendcomment($meeting_id,$comment_id){
        $this->Meeting->bindModel(array(
            'hasAndBelongsToMany'=>array(
                'User'=>array('with'=>'Attendance'),
            )
        ),false);
        $meeting=$this->Meeting->read(null,$meeting_id);
        $this->Comment->bindModel(array(
            'belongsTo'=>array(
                'User',
            )
        ),false);
        $comment=$this->Comment->read(null,$comment_id);
        $meeting['Comment']['comment']=$comment['Comment']['description'];
        $meeting['Comment']['user']=$comment['User']['name'];
        $meeting['Link']['meeting']=array('committee'=>urlencode($this->dcommittee['Committee']['short_name']),'controller'=>'meetings','action'=>'view','id'=>$meeting_id);
        $template=$this->Template->processTemplate('meeting comment',$meeting);
        if($template){
            foreach($meeting['User'] as $user){
                $this->Meeting->sendEmail($meeting['Meeting'],$template,$user,null);
            }    
        }
    }

    /**
     * Describe edit
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function edit($committee=null,$id = null) {
        $this->Meeting->unbindmodel(array('hasMany'=>array('Decision','Todo')));
        $this->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        
        //check permission
        if($this->Auth->user('superuser')==0 && empty($this->data['MeetingComment']['Comment']['description'])){
            $permit=$this->meetingPermission($id,array('Edit'));
            if(empty($permit['Edit'])){
                $this->notpermit();
            }
        }
        
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid Meeting', true));
            $this->redirect(array('action'=>'index'));
        }
        if (!empty($this->data)) {
            $old_attendance=$this->Meeting->Attendance->find('all',array('conditions'=>array('Attendance.deleted'=>0,'Attendance.meeting_id'=>$id))); 
            //save comment in meeting view
            if(isset($this->data['Meeting']['returnpage'])){
                if ($this->Meeting->save($this->data)) {
                    if(isset($this->data['MeetingComment']['Comment']) && configure::read('e_meetingcomment')==1){
                        $this->Comment=ClassRegistry::init('Comment','model');
                        $this->sendcomment($this->data['Meeting']['id'],$this->Comment->getLastInsertID());
                    }
                    $this->redirect($this->data['Meeting']['returnpage']);
                }
            }
            
            //check the number of chairperson
            $chairperson=$this->Meeting->Attendance->CheckChairperson($this->data['User']);
            if($chairperson==0){
                $this->Session->setFlash(__('Please choose a member as chairperson.', true));
                $this->redirect(array('committee'=>$committee,'controller'=>'meetings','action'=>'edit','id'=>$id));
            }elseif($chairperson>1){
                $this->Session->setFlash(__('You have choosen more than one chairperson. Only one member is allowed to be chairperson.', true));
                $this->redirect(array('committee'=>$committee,'controller'=>'meetings','action'=>'edit','id'=>$id));
            }elseif($this->Meeting->Attendance->CheckSecretariat($this->data['User'])==0){
                $this->Session->setFlash(__('Please select the secretariat.', true));
                $this->redirect(array('committee'=>$committee,'controller'=>'meetings','action'=>'edit','id'=>$id));
            }else{
                if(configure::read('e_invite')==1){
                    $prev_invited_users=$this->Meeting->prev_invited_users($this->data);
                
                    $this->data['Session']['user_id']=$this->Auth->user('id');
                    //previous meeting data
                    $prev_meeting=$this->Meeting->read(null,$this->data['Meeting']['id']);
                    //check the time and venue in last sent message
                    $last_notify=$this->Meeting->Notification->find('first',array('field'=>'data','conditions'=>array('meeting_id'=>$this->data['Meeting']['id'],'notification_sent'=>1,'type'=>array('invite','change','uninvite')),'order'=>'Notification.notification_date desc'));
                    if(!empty($last_notify['Notification']['data'])){
                        $last_message=$last_notify['Notification']['data'];
                        $pos1=strpos($last_message,'meeting_date');
                        $pos2=strpos($last_message,'venue');
                        $pos3=strrpos($last_message,"'");
                        $prev_meeting['Meeting']['meeting_date']= substr($last_message,$pos1+15,19);
                        $prev_meeting['Meeting']['venue']=substr($last_message,$pos2+8,$pos3-$pos2-8);
                    }
                    $this->Session->write('prev_meeting',$prev_meeting);
                }
                if ($this->Meeting->save($this->data)) {
                    $this->Meeting->create_cal($this->dcommittee['Committee']['id']);
                    $meeting=$this->Meeting->read(null,$this->data['Meeting']['id']);
                    // save member attending as who
                    $this->Meeting->Attendance->updateAttendance($old_attendance,$this->data,$this->data['Meeting']['id']);
                
                    $attendance = $this->Meeting->Attendance->find('all',array('conditions'=>array('Meeting.id'=>$this->data['Meeting']['id']))); 
                    foreach(array_merge($old_attendance,$attendance) as $a){
                        $this->Meeting->create_usercal($a['User']['id'],$a['User']['username']);
                    }
                   
                    // update data inside hash table for attendance confirmation
                    $this->Hash->updateHash($old_attendance,$attendance);
                    //delete all the unsent notification data 
                    $this->Session->setFlash(__('The Meeting has been saved', true));
                    if(configure::read('e_invite')==1){
                        $this->Meeting->Notification->deleteAll(array('meeting_id'=>$this->data['Meeting']['id'],'notification_sent'=>0,'type'=>array('invite','change','uninvite')));
                        if(!$this->Meeting->Notification->find('count',array('conditions'=>array('meeting_id'=>$this->data['Meeting']['id'],'notification_sent'=>1,'type'=>array('invite','change','uninvite'))))){  
                            //notification has never been sent
                            $this->redirect(array('committee'=>$this->dcommittee['Committee']['short_name'],'action'=>'invite','id'=>$this->data['Meeting']['id']));
                        }else{ 
                            //notification has been sent already so please send changes
                            $new_invited_users = Set::extract($attendance,'{n}.User.id');
                            $to_invite = array_diff($new_invited_users, $prev_invited_users);
                            $to_uninvite = array_diff($prev_invited_users, $new_invited_users);
                            $to_notify_changes = array();
                            if (array_diff($prev_meeting['Meeting'],$meeting['Meeting'])){
                            //check whether have difference between current meeting and data in last sent message
                                $to_notify_changes = array_intersect($prev_invited_users, $new_invited_users);
                            }    
                          
                            $this->Session->write('to_invite',$to_invite);
                            $this->Session->write('to_uninvite',$to_uninvite);
                            $this->Session->write('to_notify_changes',$to_notify_changes);
            
                            $this->set('to_invite',set::extract($this->Meeting->User->find('all',array('conditions'=>array('User.id'=>$to_invite))),'{n}.User.name'));
                            $this->set('to_uninvite',set::extract($this->Meeting->User->find('all',array('conditions'=>array('User.id'=>$to_uninvite))),'{n}.User.name'));
                            $this->set('to_notify_changes',set::extract($this->Meeting->User->find('all',array('conditions'=>array('User.id'=>$to_notify_changes))),'{n}.User.name'));
                        
                            $meeting['OldMeeting']=$prev_meeting['Meeting'];
                            $meeting['Link']['meeting']=array('committee'=>urlencode($this->dcommittee['Committee']['short_name']),'controller'=>'meetings','action'=>'view','id'=>$id);
                        
                            $this->set('invite',$this->Template->processTemplate('invite',$meeting));
                            $this->set('change',$this->Template->processTemplate('change',$meeting));
                            $this->set('uninvite',$this->Template->processTemplate('uninvite',$meeting));
                            $this->set('meeting',$meeting);
                            $this->render('previewemails');
                        }
                    }else{
                            $this->redirect(array('committee'=>$this->dcommittee['Committee']['short_name'],'action'=>'index'));
                        }
                }else {
                    $this->Session->setFlash(__('The Meeting could not be saved. Please, try again.', true));
                }
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Meeting->read(null, $id);
        }
        $this->set('data',$this->data);
        $users = $this->Meeting->Attendance->User->getUsersPerCommitteeList($this->dcommittee['Committee']['id']);
        $users2 = $this->Meeting->Attendance->find('all',array('conditions'=>array('meeting_id'=>$id,'Attendance.deleted'=>array(0,1)),'fields'=>'Attendance.*'));
        $this->set('groups',$this->Meeting->Attendance->User->Group->find('list',array('conditions'=>array('committee_id'=>$this->dcommittee['Committee']['id']))));
        $this->set(compact('users'));
        $this->set(compact('users2'));
    }

    /**
     * Describe delete
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function delete($committee,$id = null) {
        $dcommittee=$this->Meeting->Committee->findByShortName($committee);
        $this->set('dcommittee',$dcommittee);
        if($this->Auth->user('superuser')==0){
            $permit=$this->meetingPermission($id,array('Delete'));
            if(empty($permit['Delete'])){
                $this->notpermit();
            }
        }
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for Meeting', true));
            $this->redirect(array('committee'=>$dcommittee['Committee']['short_name'],'controller'=>'meetings','action'=>'index'));
        }
        
        $meeting=$this->Meeting->read(null,$id);
        
        $this->Meeting->unbindModel(array('hasAndBelongsToMany'=>array('User')),false);
        $this->Meeting->delete($id);
        if(!empty($meeting['User'])){
            foreach($meeting['User'] as $u){
                $this->Meeting->create_usercal($u['id'],$u['username']);
            }
        }
        $this->Meeting->create_cal($this->dcommittee['Committee']['id']);
        $this->Session->setFlash(__('Meeting deleted', true));
        if(configure::read('e_inivite')==1){
            $this->redirect(array('committee'=>$dcommittee['Committee']['short_name'],'action'=>'cancel','id'=>$id));
        }else{
            $this->redirect(array('committee'=>$dcommittee['Committee']['short_name'],'action'=>'index'));
        }
    }


    /////////////////////// ajax functions ///////////////////////

    /**
     * Describe getvenue
     *
     * @return null
     */
    function getvenue() {
        Configure::write('debug', 1); // dont want debug in ajax returned html
        if ($this->RequestHandler->isAjax()) {
            $this->Meeting->recursive=-1;
            $ddat=$this->Meeting->findDistinct(array('Meeting.venue LIKE '=> '%'.$this->data['Meeting']['venue'].'%'),'venue');
            $this->set('ddat',$ddat);
            $this->render('getvenue','ajax');
        }
    }

    /**
     * Describe attendance
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function attendance($committee=null,$id = null) { 
        $this->Meeting->Committee->unbindmodel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Userstatus','Groupstatus','Wfmodel','Todo'),'hasAndBelongsToMany'=>array('User')),false);
        $this->Meeting->Behaviors->detach('MultiFile');
        $this->Meeting->Behaviors->detach('Comment');
        $this->Meeting->unbindmodel(array('hasMany'=>array('Decision','Notification','Todo'),'hasAndBelongsToMany'=>array('User')),false);
        
        $this->set('dcommittee',$this->dcommittee); 
        if (!$id && empty($this->data)) { 
            $this->Session->setFlash(__('Invalid Meeting', true)); 
            $this->redirect(array('committee'=>$this->dcommittee['Committee']['id'],'action'=>'index')); 
        } 
        if($this->data){ 
            $this->Meeting->Attendance->saveData($this->data);
            $this->redirect(array('committee'=>$this->dcommittee['Committee']['short_name'],'action'=>'attendance','id'=>$id)); 
        } 

        $committee = $this->params['committee'];
        $meetingId = $this->params['id'];       
        $invitees = $this->Meeting->attendancelist($meetingId, $committee);
        
        //permission
        $permission=$this->permission;
        $permit=$permission['Attendance']['View'];
        if((isset($permission['Attendance']['Edit']) && $permission['Attendance']['Edit'])){
            $this->set('allow_edit',true);
        }elseif(in_array($this->Auth->user('id'),set::extract($invitees,'{n}.Attendance.user_id'))){
            $permit+=$permission['Attendance -Invited']['View'];
            if($permission['Attendance -Invited']['Edit']){
                $this->set('allow_edit',true);
            }else{
                $no=array_search($this->Auth->user('id'),set::extract($invitees,'{n}.Attendance.user_id'));
                if($invitees[$no]['Attendance']['attend_as']==1){
                    $permit+=1;
                    $this->set('allow_edit',true);
                }
            }
        }
        if($permit==0){
            $this->notpermit();
        }
        
        //$invitees = $this->User->Protocol->softByProtocol($invitees);
        $getMeeting = $this->Meeting->query("SELECT id, allow_representative FROM meetings WHERE id=".$meetingId );

        $this->set('getMeeting', $getMeeting);
        $this->set('invitees', $invitees); 
        // get meeting details 
        $this->set('meeting', $this->Meeting->read(null, $id)); 
    }
    /**
     * Describe announce minute(view)
     *
     * @param $committee
     * @param $id --meeting id
     * @return null
     */
    function announceminute($committee,$id){
        $this->Meeting->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Meeting->unbindModel(array('hasMany'=>array('Decision','Todo','Notification'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Meeting->Behaviors->detach('MultiFile');
        $this->Meeting->Behaviors->detach('Comment');
        
        $meeting=$this->Meeting->read(null,$id);
        if(!$this->Notification->checkSent($id,'minutes approved') || !$this->Meeting->Attendance->isSecretariat($id,$this->Auth->User('id'))){
            $this->notpermit();
        }
        $meeting['Updater']=$this->Auth->user('name');
        $meeting['Link']['meeting']=array('committee'=>$committee,'controller'=>'decisions','action'=>'printminutes','id'=>$id);
        $template=$this->Template->processTemplate('announce minute',$meeting);
        
        $this->set('template',$template);
        $this->set('committee',$committee);
        $this->set('id',$id);   
    } 
    
     /**
     * Describe sendAnnounce 
     * send announce minute email
     * @param $committee
     * @param $id--meeting id
     * @return null
     */
    function sendAnnounce($committee,$id){
        //only allowed after announceminute page
        if(!strpos($this->Session->read('history'),'meetings/announceminute')){
            $this->notpermit();
        }
        $meeting=$this->Meeting->read(null,$id);
        $meeting['Updater']=$this->Auth->user('name');
        $meeting['Link']['meeting']=array('committee'=>$committee,'action'=>'minutes','id'=>$id);
        $template=$this->Template->processTemplate('announce minute',$meeting);
        
        if (!empty($meeting['User'])){
            foreach($meeting['User'] as $user){ 
                $this->Meeting->sendEmail($meeting['Meeting'],$template,$user,null);
            }
            $this->Session->setFlash(__('The announcement of minute availability has been sent', true));
        }
        $this->redirect(array('committee'=>$committee,'action'=>'view','id'=>$id));
    }
    
    /**
     * Describe approval
     * the view user sees before sending the email
     * @param $committee
     * @param $id --meeting id
     * @return null
     */
    function approval($committee,$id,$re=null){
        $this->Meeting->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Meeting->unbindModel(array('hasMany'=>array('Decision','Todo'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Meeting->Behaviors->detach('MultiFile');
        $this->Meeting->Behaviors->detach('Comment');
        
        $meeting=$this->Meeting->read(null,$id);
        
        //check permission --just for not approved minute and secretariat
        if(in_array('minutes approved',Set::extract($meeting,'Notification.{n}.type')) || !$this->Meeting->Attendance->isSecretariat($meeting['Meeting']['id'],$this->Auth->user('id'))){
            $this->notpermit();
        }
        $meeting['Link']['meeting']=array('committee'=>$committee,'controller'=>'decisions','action'=>'printminutes','id'=>$id);
        if(!empty($re)){
            $template=$this->Template->processTemplate('send for reapproval',$meeting);
        }else{
            $template=$this->Template->processTemplate('send for approval',$meeting);
        }
        
        $this->set('template',$template);
        $this->set('committee',$committee);
        $this->set('id',$id);   
        $this->set('re',$re);   
    } 
    
    /**
     * Describe approval
     * the email sent for approval
     * @param $committee
     * @param $id --meeting id
     * @return null
     */
    function send_approval($committee,$id,$re=null){

        $meeting=$this->Meeting->read(null,$id);
        $meeting['Link']['meeting']=array('committee'=>$committee,'controller'=>'decisions','action'=>'printminutes','id'=>$id);
        if(!empty($re)){
            $template=$this->Template->processTemplate('send for reapproval',$meeting);
        }else{
            $template=$this->Template->processTemplate('send for approval',$meeting);
        }
        
        $approver=$this->Meeting->Attendance->getApprover($meeting);
        if (!empty($approver)) {
            foreach($approver as $chairperson){
                $this->Meeting->sendEmail($meeting['Meeting'],$template,$chairperson['User'],null);
                $this->Session->setFlash(__('Notification has been sent to the chairperson', true));
            }
        }
        $this->redirect(array('committee'=>$committee,'action'=>'view','id'=>$id));
    }
        
    /**
     * chairperson approve the minutes
     */ 
    function approve_minutes($committee,$id) {
        $this->Meeting->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Meeting->unbindModel(array('hasMany'=>array('Decision','Todo','Notification'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Meeting->Behaviors->detach('MultiFile');
        $this->Meeting->Behaviors->detach('Comment');
        
        $chairperson = $this->Meeting->Attendance->find('first',array('conditions'=>array('meeting_id'=>$id,'attend_as'=>'2')));
        $permission=$this->Session->read('permission');
        //check permission -- just for chairperson
        if($chairperson['User']['id']!=$this->Auth->user('id') && empty($permission['Minute approval']['Create'])){
            $this->notpermit();
        }
        $meeting=$this->Meeting->read(null,$id);
        $meeting['chairperson']=$chairperson['User']['name'];
        $meeting['Link']['meeting']=array('committee'=>$committee,'action'=>'minutes','id'=>$id);
        $template=$this->Template->processTemplate('minutes approved',$meeting);
        
        $secretariat = $this->Meeting->Attendance->find('all',array('conditions'=>array('meeting_id'=>$id,'attend_as'=>'1')));
        
        if (count($secretariat)) {
            foreach($secretariat as $sec){ 
                $this->Meeting->sendEmail($meeting['Meeting'],$template,$sec['User'],null);
            }
        }
        
        $this->redirect(array('committee'=>$committee,'controller'=>'decisions','action'=>'printminutes','id'=>$id,__('Notification has been sent to the secretariat', true)));
    }
    
    /*describe approved all decision
     * */
    function approvedecision($committee,$meetingid) {
		$decisions=$this->Meeting->Decision->find('all',array('conditions'=>array('Decision.meeting_id'=>$meetingid,'Decision.approved'=>0)));
		foreach($decisions as $d){
			$d['Decision']['approved'] = 1;
			$this->Decision->save($d,false);
		}
			
        $this->Session->setFlash(sprintf(__('All decision had been put into the minutes',true)));
        $this->redirect(array('committee'=>$committee,'id'=>$meetingid,'action'=>'view'));          
    }

}
?>
